package com.jgp.security.shiro.filter;

import com.jgp.common.type.EndPointType;
import com.jgp.common.utils.JGPUtil;
import com.jgp.security.shiro.exception.SecurityErrorCode;
import com.jgp.security.shiro.exception.SecurityException;
import com.jgp.security.shiro.pojo.JgpUsernamePasswordToken;
import com.jgp.sys.ui.Result;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/3/12
 */
public class NormalAuthenticationFilter extends FormAuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger(NormalAuthenticationFilter.class);
    
    public NormalAuthenticationFilter() {
        this.setLoginUrl("/security/entry-ctl/login");
        this.setUsernameParam("admin_name");
        this.setPasswordParam("admin_pwd");
        this.setRememberMeParam("admin_remember_me");
    }
    
    /**
     * 在访问过来的时候检测是否为OPTIONS请求，如果是就直接返回true
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            setHeader(httpRequest, httpResponse);
            return true;
        }
        return super.preHandle(request, response);
    }
    
    /**
     * 为response设置header，实现跨域
     */
    private void setHeader(HttpServletRequest request, HttpServletResponse response) {
        //跨域的header设置
        response.setHeader("Access-control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        //防止乱码，适用于传输JSON数据
        //response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
    }
    
    @Override
    protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
        return super.isLoginSubmission(request, response);
    }
    
    @Override
    protected AuthenticationToken createToken(String username, String password, boolean rememberMe, String host) {
        return new JgpUsernamePasswordToken(username, password, rememberMe, host, EndPointType.PC);
    }
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String accept = ((HttpServletRequest) request).getHeader("accept");
        if (accept == null || accept.toLowerCase().contains("application/json")) {
            Result result = new Result();
            SecurityException error = new SecurityException(SecurityErrorCode.AUTHENTICATION_FAIL);
            result.flag(false).error(error.getCode(), error.getMessage(), error.getModule());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JGPUtil.toJson(result));
            return false;
        }else{
            return super.onAccessDenied(request, response);
        }
    }
}
